package com.example.jwt.config;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.IORuntimeException;
import com.alibaba.fastjson.JSON;
import com.example.jwt.annotation.PermissionsInterceptor;
import com.example.jwt.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * MVC配置
 * @author mtl
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private LoginUserHandlerMethodArgumentResolver loginUserHandlerMethodArgumentResolver;

    @Resource
    private Interceptor interceptor;

    @Resource
    private PermissionsInterceptor permissionsInterceptor;

    @Value("${server.servlet.context-path}")
    private String path;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //监听过滤器
        registry.addInterceptor(interceptor).addPathPatterns("/**")
                .excludePathPatterns("/admin/login").excludePathPatterns(path+"/user/login").excludePathPatterns("/home/**");

        // 权限认证
        registry.addInterceptor(permissionsInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/admin/login").excludePathPatterns("**/user/login").excludePathPatterns("/home/**");;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        //参数解析器
        argumentResolvers.add(loginUserHandlerMethodArgumentResolver);
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }

    /**
     * 过滤器返回异常结果集
     * @param msg 结果提示语
     */
    public static void writer(String msg,HttpServletResponse response){
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer=null;
        try {
            writer=response.getWriter();
            writer.write(JSON.toJSONString(R.error(msg)));
            writer.flush();
        } catch (IOException ex) {
            throw ExceptionUtil.wrap(new IOException("操作失败！"), IORuntimeException.class);
        }finally {
            if(writer!=null) {
                writer.close();
            }
        }
    }

}